import React, { Component } from 'react'
import { connect } from 'dva';

import { Table, Popconfirm, Divider } from 'antd';
import Form from './components/SearchForm';
import { checkInit, getFileType } from '@/utils/util';
import { UmiComponentProps, BaseComponentProps } from '@/common/type';
import Imgviewer from '@/components/ImgViewer';
import Fileviewer from '@/components/FileViewer';

export interface P {
  children?: React.ReactNode,
  list: {
    data: Array<any>,
    dataCnt: number
  },
  cond?: {
    pageNum: string,
    pageSize: string
  },
}

type Props = P & UmiComponentProps & BaseComponentProps;

@connect(({ account, loading, menu }) => ({
  list: account.list || {},
  dict: account.dict,
  cond: account.cond,
  buttons: menu.buttons,
  loading: loading.effects['account/queryPage']
}))
class Account extends Component<Props, any> {
  constructor(props) {
    super(props);
    this.initCurrent = this.initCurrent.bind(this);
  }
  state = {
    current: 1,
    office: true
  };

  queryData(offset = 1) {
    const { dispatch } = this.props;

    dispatch({
      type: 'account/queryPage',
      payload: {
        pageNum: offset,
      },
    });
  }

  remove = (id: string) => {
    const { dispatch } = this.props;
    this.setState({
      current: 1
    }, () => {
      dispatch({
        type: 'account/remove',
        payload: id
      })
    })
  }

  initCurrent() {
    this.setState({
      current: 1
    })
  }

  onShowSizeChange = (current, pageSize) => {
    const { dispatch, cond } = this.props;
    cond.pageSize = pageSize;
    dispatch({ type: `account/updateCond`, payload: cond }).then(() => {
      this.initCurrent()
    })
  }

  componentDidMount() {
    const { dispatch } = this.props;
    checkInit() ? dispatch({ type: `account/initCond` }) : this.queryData();
  }

  render() {
    const { buttons } = this.props;
    const btnList = {};
    if (Array.isArray(buttons)) {
      buttons.forEach(item => {
        btnList[item.name] = item.name
      });
    }
    const { data = [], dataCnt } = this.props.list;
    const ans = Array.isArray(data) ? data.map((v, index) => ({
      ...v,
      ind: index + 1 < 10 ? `0${index + 1}` : index + 1,
    })) : []

    const pagination = {
      total: dataCnt,
      showTotal: total => `共 ${total} 条`,
      showSizeChanger: true,
      pageSizeOptions: ['10', '20', '50', '100'],
      onShowSizeChange: this.onShowSizeChange,
      onChange: (current) => {
        this.setState({ current });
        this.queryData(current)
      },
    };
    const columns = [{
      title: '名称',
      dataIndex: 'name',
    }, {
      title: '台账类型',
      dataIndex: 'typeName',
    }, {
      title: '上传时间',
      dataIndex: 'createTime',
    }, {
      title: '操作', key: 'x', render: (record, text, index) => {
        return (
          <div style={{ display: 'flex' }}>
            <>
                {
                  getFileType(record.url) === 'image' 
                    ? <Imgviewer hasText='查看' missText="" url={record.url} icon={false}/>
                    : (getFileType(record.url) === 'office' || (getFileType(record.url) === 'pdf')) 
                      ? <Fileviewer url={record.url}/>
                      : <a href={`${record.url}`}>查看</a>
                }
                <Divider type="vertical" />
              </>
            {
              btnList['删除'] &&
              <Popconfirm title="请确认是否删除?" onConfirm={() => this.remove(record.id)} okText="确定" cancelText="取消">
                <a>删除</a>
              </Popconfirm>
            }
          </div>
        )
      }
    }];
    return (
      <>
        <Form current={this.state.current} initCurrent={this.initCurrent} new={!!btnList['上传']} />
        <Table
          columns={[{
            title: '序号',
            dataIndex: 'ind',
          }, ...columns]}
          pagination={pagination}
          dataSource={ans}
          bordered
          rowKey="id"
          loading={this.props.loading}
        />
      </>
    );
  }
}

export default Account;
